//
//  XGRegisterViewController.m
//  Instagram
//
//  Created by monkey on 2019/4/13.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <AVOSCloud/AVOSCloud.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import <TZImagePickerController/TZImagePickerController.h>

#import "XGRegisterViewController.h"

@interface XGRegisterViewController () <TZImagePickerControllerDelegate>

/// 容器视图
@property (nonatomic,strong) UIScrollView *contentView;
/// 头像
@property (nonatomic,strong) UIImageView *userIconImageView;
/// 邮箱
@property (nonatomic,strong) UITextField *emailTextField;
/// 密码
@property (nonatomic,strong) UITextField *passwordTextField;
/// 确认密码
@property (nonatomic,strong) UITextField *confirmPasswordTextField;
/// 昵称
@property (nonatomic,strong) UITextField *userNameTextField;
/// 个人简介
@property (nonatomic,strong) UITextView *descriptionTextView;
/// 性别选择器
@property (nonatomic,strong) UISegmentedControl *genderSegmentedControl;
/// 注册按钮
@property (nonatomic,strong) UIButton *registerButton;
/// 取消按钮
@property (nonatomic,strong) UIButton *cancelButton;

@end

@implementation XGRegisterViewController

#pragma mark - 控制器生命周期方法

- (void)loadView
{
    [super loadView];
    
    [self setUpUI];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchViewForHiddenKeyboardAction)];
    [self.view addGestureRecognizer:tap];
    
    // 注册通知 监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc
{
    // 注销通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 事件监听

/// 隐藏键盘事件
- (void)touchViewForHiddenKeyboardAction
{
    [self.view endEditing:YES];
}

/// 注册事件
- (void)registerAction
{
    // 退出键盘
    [self.view endEditing:YES];
    
    // 判断字段是否为空
    if (!_emailTextField.hasText ||
        !_passwordTextField.hasText ||
        !_confirmPasswordTextField.hasText ||
        !_userNameTextField.text ) {
        [SVProgressHUD showErrorWithStatus:@"请填写完所有字段"];
        return;
    }
    
    // 验证邮箱格式
    if (!_emailTextField.text.isEmail) {
        [SVProgressHUD showErrorWithStatus:@"邮箱格式不正确!请检查后重新填写"];
        return;
    }
    
    // 验证密码长度 需要 >= 6 <= 10
    if (_passwordTextField.text.length < 6 || _passwordTextField.text.length > 10) {
        [SVProgressHUD showErrorWithStatus:@"密码长度需要在6~10位"];
        return;
    }
    
    // 验证确认密码
    if (![_confirmPasswordTextField.text isEqualToString:_passwordTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"密码与确认密码不一致"];
        return;
    }
    
    // 注册
    XGGenderType gender = _genderSegmentedControl.selectedSegmentIndex == 0 ? XGGenderTypeMale : XGGenderTypeFemale;
    [XGAccountViewModel registerAccountWithEmail:_emailTextField.text password:_passwordTextField.text screenName:_userNameTextField.text gender:gender descriptionInfo:_descriptionTextView.text userIcon:_userIconImageView.image completion:^(BOOL isSuccess, NSString * _Nonnull message) {
        if (isSuccess) {
            [SVProgressHUD showSuccessWithStatus:message];
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
        
        [self goBackAction];
    }];
}

/// 退出注册页面事件
- (void)goBackAction
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

/// 键盘即将显示通知监听
- (void)keyboardWillShowNotification:(NSNotification *)notification
{
    /*
     UIKeyboardAnimationDurationUserInfoKey = "0.25";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 407}, {375, 260}}";
     }
     */
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    _contentView.frame = CGRectMake(0, 0, self.view.width, self.view.height - rect.size.height);
}

/// 键盘即将消失通知监听
- (void)keyboardWillHideNotification:(NSNotification *)notification
{
     _contentView.frame = self.view.bounds;
}

/// 从相册选择照片
- (void)pickerImageFromPhotosAction
{
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - 代理

/// 从相册取回图片代理
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    _userIconImageView.image = photos.firstObject;;
}

#pragma mark - 设置界面

/// 设置界面
- (void)setUpUI
{
    self.view.backgroundColor = [UIColor red:210 green:254 blue:91 alpha:1];
    self.contentView.backgroundColor = self.view.backgroundColor;
    
    // 添加子控件
    [self.view addSubview:_contentView];
    
    // 设置布局
    _contentView.frame = self.view.bounds;
    _contentView.contentSize = _contentView.size;
    
    [self setUpContentView];
}

/// 设置scrollView容器视图
- (void)setUpContentView
{
    // 添加控件
    [_contentView addSubview:self.userIconImageView];
    [_contentView addSubview:self.emailTextField];
    [_contentView addSubview:self.passwordTextField];
    [_contentView addSubview:self.confirmPasswordTextField];
    [_contentView addSubview:self.userNameTextField];
    [_contentView addSubview:self.descriptionTextView];
    [_contentView addSubview:self.genderSegmentedControl];
    [_contentView addSubview:self.registerButton];
    [_contentView addSubview:self.cancelButton];
    
    // 设置布局
    CGFloat textFieldWidth = _contentView.width - 20 * 2;
    CGFloat textFieldHeight = 36;
    _userIconImageView.frame = CGRectMake((_contentView.width - 80) / 2, 30, 80, 80);
    _emailTextField.frame = CGRectMake(20, _userIconImageView.maxY + 15, textFieldWidth, textFieldHeight);
    _passwordTextField.frame = CGRectMake(20, _emailTextField.maxY + 15, textFieldWidth, textFieldHeight);
    _confirmPasswordTextField.frame = CGRectMake(20, _passwordTextField.maxY + 15, textFieldWidth, textFieldHeight);
    _userNameTextField.frame = CGRectMake(20, _confirmPasswordTextField.maxY + 15, textFieldWidth, textFieldHeight);
    _descriptionTextView.frame = CGRectMake(20, _userNameTextField.maxY + 15, textFieldWidth, 100);
    _genderSegmentedControl.frame = CGRectMake(20, _descriptionTextView.maxY + 15, 80, 36);
    _registerButton.frame = CGRectMake(20, _genderSegmentedControl.maxY + 15, 80, 36);
    _cancelButton.frame = CGRectMake(_contentView.width - 20 - 80, _genderSegmentedControl.maxY + 15, 80, 36);

    // 设置头像圆角
    _userIconImageView.layer.cornerRadius = _userIconImageView.width / 2;
    _userIconImageView.layer.masksToBounds = YES;
}

#pragma mark - 懒加载

- (UIScrollView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIScrollView alloc] init];
    }
    
    return _contentView;
}

- (UIImageView *)userIconImageView
{
    if (!_userIconImageView) {
        _userIconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"avatar_default"]];
        _userIconImageView.userInteractionEnabled = YES;
        [_userIconImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickerImageFromPhotosAction)]];
    }
    
    return _userIconImageView;
}

- (UITextField *)emailTextField
{
    if (!_emailTextField) {
        _emailTextField = [UITextField textFieldWithPlaceholder:@"邮箱地址(必填)" fontSize:15 textColor:[UIColor darkTextColor] isSecureTextEntry:NO keyboardType:UIKeyboardTypeEmailAddress];
    }
    
    return _emailTextField;
}

- (UITextField *)passwordTextField
{
    if (!_passwordTextField) {
        _passwordTextField = [UITextField textFieldWithPlaceholder:@"密码(必填)" fontSize:15 textColor:[UIColor darkTextColor] isSecureTextEntry:YES keyboardType:UIKeyboardTypeDefault];
    }
    
    return _passwordTextField;
}

- (UITextField *)confirmPasswordTextField
{
    if (!_confirmPasswordTextField) {
        _confirmPasswordTextField = [UITextField textFieldWithPlaceholder:@"确认密码(必填)" fontSize:15 textColor:[UIColor darkTextColor] isSecureTextEntry:YES keyboardType:UIKeyboardTypeDefault];
    }
    
    return _confirmPasswordTextField;
}

- (UITextField *)userNameTextField
{
    if (!_userNameTextField) {
        _userNameTextField = [UITextField textFieldWithPlaceholder:@"昵称(必填)" fontSize:15 textColor:[UIColor darkTextColor] isSecureTextEntry:NO keyboardType:UIKeyboardTypeDefault];
    }
    
    return _userNameTextField;
}

- (UISegmentedControl *)genderSegmentedControl
{
    if (!_genderSegmentedControl) {
        _genderSegmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"男",@"女"]];
        _genderSegmentedControl.selectedSegmentIndex = 0;
        [_genderSegmentedControl sizeToFit];
    }
    
    return _genderSegmentedControl;
}

- (UITextView *)descriptionTextView
{
    if (!_descriptionTextView) {
        _descriptionTextView = [[UITextView alloc] init];
        _descriptionTextView.font = [UIFont systemFontOfSize:15];
        [_descriptionTextView setPlaceholderWithText:@"个人简介(非必填)" Color:[UIColor lightGrayColor]];

    }
    
    return _descriptionTextView;
}

- (UIButton *)registerButton
{
    if (!_registerButton) {
        _registerButton = [UIButton buttonWithTitle:@"注册" fontSize:15 titleColor:[UIColor whiteColor] target:self action:@selector(registerAction)];
        _registerButton.backgroundColor = [UIColor orangeColor];
    }
    
    return _registerButton;
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithTitle:@"取消" fontSize:15 titleColor:[UIColor whiteColor] target:self action:@selector(goBackAction)];
        _cancelButton.backgroundColor = [UIColor red:245 green:90 blue:93 alpha:1];
    }
    
    return _cancelButton;
}

@end
